"""
数据库模型定义
"""

import uuid
from datetime import datetime
from sqlalchemy import Column, String, Text, ForeignKey, DateTime, Index, Boolean
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from app.database import Base


class User(Base):
    """用户表 - 认证核心"""

    __tablename__ = "users"

    user_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    username = Column(String(50), unique=True, nullable=False, index=True)
    email = Column(String(100), unique=True, nullable=False, index=True)
    hashed_password = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=datetime.now)

    # 关系
    interview_sessions = relationship("InterviewSession", back_populates="user")


class Position(Base):
    """岗位表 - RAG 链接"""

    __tablename__ = "positions"

    position_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    title = Column(String(100), nullable=False)
    jd_text = Column(Text, nullable=False)
    white_paper_tag = Column(String(100), nullable=False, index=True)
    created_at = Column(DateTime, default=datetime.now)

    # 关系
    interview_sessions = relationship("InterviewSession", back_populates="position")


class InterviewSession(Base):
    """会话表 - 用户资产"""

    __tablename__ = "interview_sessions"

    session_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.user_id"), nullable=False)
    position_id = Column(
        UUID(as_uuid=True), ForeignKey("positions.position_id"), nullable=False
    )
    cv_text = Column(Text, nullable=False)
    analysis_report = Column(Text, nullable=True)
    is_ended = Column(Boolean, default=False, nullable=False)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(
        DateTime,
        default=datetime.now,
        onupdate=datetime.now,
    )

    # 关系
    user = relationship("User", back_populates="interview_sessions")
    position = relationship("Position", back_populates="interview_sessions")
    chat_messages = relationship(
        "ChatMessage", back_populates="session", cascade="all, delete-orphan"
    )

    # 索引
    __table_args__ = (Index("idx_user_sessions", "user_id", "created_at"),)


class ChatMessage(Base):
    """聊天记录表 - 对话历史"""

    __tablename__ = "chat_messages"

    message_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    session_id = Column(
        UUID(as_uuid=True), ForeignKey("interview_sessions.session_id"), nullable=False
    )
    role = Column(String(20), nullable=False)  # 'human', 'ai', 'tool', 'tool_result'
    content = Column(Text, nullable=False)
    tool_name = Column(
        String(100), nullable=True
    )  # 工具名称（仅当role为tool或tool_result时）
    is_internal = Column(
        Boolean, default=False, nullable=False
    )  # True表示内部消息（工具调用），不返回给用户
    timestamp = Column(DateTime, default=datetime.now, index=True)

    # 关系
    session = relationship("InterviewSession", back_populates="chat_messages")

    # 索引
    __table_args__ = (Index("idx_session_messages", "session_id", "timestamp"),)
